package org.os.framework.extensions.web.wrapper;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

/**
 * @author
 */
public class DecryptHttpRequest extends HttpServletRequestWrapper {

    private byte[] body;
    private ServletInputStream inputStream;

    public DecryptHttpRequest(HttpServletRequest request) throws IOException {
        super(request);
        // 将原始请求体读取到字节数组中
        StringBuilder stringBuilder = new StringBuilder();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(request.getInputStream()));
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            stringBuilder.append(line);
        }
        body = stringBuilder.toString().getBytes("UTF-8");
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        if (inputStream == null) {
            inputStream = new ServletInputStream() {
                private ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body);

                @Override
                public boolean isFinished() {
                    return false;
                }

                @Override
                public boolean isReady() {
                    return false;
                }

                @Override
                public void setReadListener(ReadListener readListener) {
                }

                @Override
                public int read() throws IOException {
                    return byteArrayInputStream.read();
                }
            };
        }
        return inputStream;
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    public void setBody(byte[] body) throws IOException {
        this.body = body;
    }

    public byte[] getBody() {
        return this.body;
    }

}
